using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ZerAx.TBON
{
    public class TbonCompound : TbonObject
    {
        static TbonCompound()
        {
            factories.Add(TbonType.Compound, (s) => new TbonCompound(s));
        }

        public override TbonType Type => TbonType.Compound;

        private List<TbonObject> children = new();

        public TbonCompound(string name) : base(name) { }
        public TbonCompound(string name, params TbonObject[] children) : this(name)
        {
            this.children.AddRange(children);
        }

        public override string GetValueString() => $"{{{string.Join(',', children.Select(x => x.Name + ":" + x.GetValueString()))}}}";

        public void AddChild(TbonObject child)
        {
            children.Add(child);
        }

        public TbonObject GetChild(string name)
        {
            return children.Find(x => x.Name == name);
        }

        public override void ReadValue(BinaryReader reader)
        {
            children.Clear();

            int len = reader.ReadInt32();
            for (int i = 0; i < len; ++i)
            {
                children.Add(Read(reader));
            }
        }

        public override void WriteValue(BinaryWriter writer)
        {
            int len = children.Count;
            writer.Write(len);
            for (int i = 0; i < len; ++i)
            {
                children[i].Write(writer);
            }
        }
    }
}